<template>
  <div
    class="marquee-container"
    :style="{ width: containerWidth + 'px' }"
    @mouseenter="pause"
    @mouseleave="resume"
  >
    <div
      class="marquee-text"
      :style="{
        transform: textOverflow ? `translateX(${offset}px)` : 'translateX(0)',
        color: color,
      }"
    >
      {{ text }}
    </div>
  </div>
</template>

<script>
export default {
  props: {
    text: {
      type: String,
      default: "",
    },
    containerWidth: {
      type: Number,
      default: 200,
    },
    speed: {
      type: Number,
      default: 20,
    },
    color: {
      type: String,
      default: "#0ba5ae",
    },
  },
  data() {
    return {
      textOverflow: false,
      offset: 0,
      isPaused: false,
      animationFrameId: null,
    };
  },
  mounted() {
    // this.judgeTextOverflow();
  },
  watch: {
    text: {
      handler(val) {
        if (val) {
          this.judgeTextOverflow();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    judgeTextOverflow() {
      // 停止旧的动画循环
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
        this.animationFrameId = null;
      }
      this.$nextTick(() => {
        const textElement = this.$el.querySelector(".marquee-text");
        this.textOverflow = textElement.offsetWidth > this.containerWidth;
        if (this.textOverflow) {
          this.startAnimation();
        }
      });
    },
    startAnimation() {
      const step = () => {
        if (!this.isPaused) {
          const textWidth = this.$el.querySelector(".marquee-text").offsetWidth;
          this.offset -= this.speed / 60;
          if (this.offset < -textWidth) {
            this.offset = this.containerWidth;
          }
        }
        this.animationFrameId = requestAnimationFrame(step);
      };
      this.animationFrameId = requestAnimationFrame(step);
    },
    pause() {
      this.isPaused = true;
    },
    resume() {
      this.isPaused = false;
      if (!this.animationFrameId) {
        this.startAnimation();
      }
    },
  },
  beforeDestroy() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/index.scss";
.marquee-container {
  overflow: hidden;
  white-space: nowrap;
}

.marquee-text {
  display: inline-block;
}
</style>
